#include "LockFile.h"

LockFile::LockFile(char* nombre) {

	strcpy(this->nombre, nombre);

	this->fl.l_type = F_WRLCK;
	this->fl.l_whence = SEEK_SET;
	this->fl.l_start = 0;
	this->fl.l_len = sizeof(PlazaEstacionamiento);
	this->fl.l_pid = getpid();
	this->fd = open(this->nombre, O_CREAT | O_WRONLY, 0777);
	//cout << "lock " << nombre << " " << this->fd << endl;
}

int LockFile::tomarLock(off_t start) {
	this->fl.l_type = F_WRLCK;
	this->fl.l_start = start;
	int resultado = fcntl(this->fd, F_SETLKW, &(this->fl));
	return resultado;
}

int LockFile::liberarLock(off_t start) {
	this->fl.l_type = F_UNLCK;
	this->fl.l_start = start;
	int resultado = fcntl(this->fd, F_SETLK, &(this->fl));
	return resultado;
}

int LockFile::escribir(char* buffer, int buffsize) {
	lseek(this->fd, 0, SEEK_END);
	int resultado = write(this->fd, buffer, buffsize);
	return resultado;
}
int LockFile::escribirConLock(char* buffer, int buffsize) {
	tomarLock(0);
	int resultado = this->escribir(buffer, buffsize);
	liberarLock(0);
	return resultado;
}

LockFile::~LockFile() {
	close(this->fd);
}
